// 配置
const API_BASE_URL = 'http://47.109.75.129:5000'; // 你的服务器地址
let socket = null;
let sensorData = {};
let alerts = [];
let deviceStatus = {};

// Chart.js实例
let waterQualityChart = null;
let environmentChart = null;

let uploadInProgress = false;
let uploadPaused = false;
let currentUploadProgress = 0;

// 传感器配置
const sensorConfig = {
    'co2': {
        name: '二氧化碳浓度',
        unit: 'ppm',
        icon: 'fas fa-wind',
        range: '300-1500 ppm',
        color: '#3498db'
    },
    'ph': {
        name: 'pH值',
        unit: '',
        icon: 'fas fa-vial',
        range: '5.5-7.0',
        color: '#9b59b6'
    },
    'tds': {
        name: 'TDS值',
        unit: 'ppm',
        icon: 'fas fa-tint',
        range: '800-1500 ppm',
        color: '#1abc9c'
    },
    'dissolved_oxygen': {
        name: '溶解氧浓度',
        unit: 'mg/L',
        icon: 'fas fa-water',
        range: '5.0-12.0 mg/L',
        color: '#2980b9'
    },
    'temperature': {
        name: '温度',
        unit: '°C',
        icon: 'fas fa-thermometer-half',
        range: '18-28 °C',
        color: '#e74c3c'
    },
    'humidity': {
        name: '湿度',
        unit: '%',
        icon: 'fas fa-cloud',
        range: '50-80%',
        color: '#3498db'
    },
    'light_intensity': {
        name: '光照强度',
        unit: 'lux',
        icon: 'fas fa-sun',
        range: '5000-30000 lux',
        color: '#f39c12'
    },
    'pest_detection': {
        name: '病虫害检测',
        unit: '',
        icon: 'fas fa-bug',
        range: '0:无, 1:有',
        color: '#e74c3c'
    }
};

// 设备配置
const deviceConfig = {
    'grow_light': { name: '补光灯', type: 'switch' },
    'alkaline_pump': { name: '碱性水泵', type: 'switch' },
    'nutrient_pump': { name: '营养液泵', type: 'switch' },
    'fan': { name: '风扇', type: 'slider' },
    'heater': { name: '加热器', type: 'switch' },
    'acid_pump': { name: '酸性水泵', type: 'switch' },
    'humidifier': { name: '加湿器', type: 'switch' }
};

// 图像和模式相关全局变量
let currentImageData = null;
let currentMode = 'stream'; // 'stream' 或 'on_demand'
let streamPaused = false;

// 初始化应用
function initApp() {
    initConnection();
    initCharts();
    initSensorCards();
    initImageDisplay();
    initModeControls();
    updateLastUpdateTime();
    
    // 每30秒更新一次最后更新时间
    setInterval(updateLastUpdateTime, 30000);
    // 每5秒更新设备状态
    setInterval(updateDeviceStatusDisplay, 5000);
}

// 初始化传感器卡片
function initSensorCards() {
    const sensorGrid = document.getElementById('sensorGrid');
    const noDataMessage = document.getElementById('noDataMessage');
    
    // 移除无数据消息
    if (noDataMessage) {
        noDataMessage.remove();
    }
    
    // 创建传感器卡片
    for (const [key, config] of Object.entries(sensorConfig)) {
        const sensorCard = document.createElement('div');
        sensorCard.className = 'sensor-card';
        sensorCard.id = `${key}-card`;
        
        sensorCard.innerHTML = `
            <div class="sensor-header">
                <div>
                    <div class="sensor-name">${config.name}</div>
                </div>
                <i class="sensor-icon ${config.icon}"></i>
            </div>
            <div class="sensor-value" id="${key}-value">--</div>
            <div class="sensor-unit">${config.unit}</div>
            <div class="sensor-range">正常范围: ${config.range}</div>
        `;
        
        sensorGrid.appendChild(sensorCard);
    }
}

// 初始化WebSocket连接
function initConnection() {
    try {
        socket = io(API_BASE_URL);
        
        socket.on('connect', function() {
            console.log('✅ 已连接到WebSocket服务器');
            updateConnectionStatus(true);
            
            // 连接成功后请求当前图像和模式状态
            requestImage();
        });
        
        socket.on('disconnect', function() {
            console.log('❌ WebSocket连接已断开');
            updateConnectionStatus(false);
        });
        
        socket.on('sensor_data', function(data) {
            console.log('📊 收到传感器数据:', data);
            processSensorData(data);
        });
        
        socket.on('connected', function(data) {
            console.log('服务器确认连接:', data);
        });
        
        socket.on('device_status_update', function(data) {
            console.log('设备状态更新:', data);
            deviceStatus = data;
            updateDeviceStatusDisplay();
        });
        
        // 新增：图像更新事件
        socket.on('image_update', function(data) {
            console.log('📷 收到图像更新');
            updateImageDisplay(data);
        });
        
        // 新增：模式更新事件
        socket.on('mode_update', function(data) {
            console.log('🔄 收到模式状态更新');
            currentMode = data.stream_mode ? 'stream' : 'on_demand';
            streamPaused = data.stream_paused;
            updateModeDisplay();
            
            if (data.message) {
                showNotification(data.message, 'success');
            }
        });
        
        socket.on('model_upload_progress', function(data) {
            console.log('📊 收到模型上传进度:', data.progress + '%');
            handleUploadProgress(data);
        });
        
        // 上传暂停监听
        socket.on('model_upload_paused', function(data) {
            console.log('⏸️ 上传已暂停');
            handleUploadPaused(data);
        });
        
        // 上传取消监听
        socket.on('model_upload_cancelled', function(data) {
            console.log('❌ 上传已取消');
            handleUploadCancelled();
        });
        
    } catch (error) {
        console.error('连接失败:', error);
        updateConnectionStatus(false);
    }
}

// 更新连接状态显示
function updateConnectionStatus(connected) {
    const indicator = document.getElementById('mqttStatusIndicator');
    const statusText = document.getElementById('mqttStatusText');
    
    if (connected) {
        indicator.className = 'status-indicator status-connected';
        statusText.textContent = 'MQTT已连接';
    } else {
        indicator.className = 'status-indicator status-disconnected';
        statusText.textContent = 'MQTT未连接';
    }
}

// 在processSensorData函数中处理病虫害数据
function processSensorData(data) {
    sensorData = data.data;
    alerts = data.alerts || [];
    
    // 特别处理病虫害检测状态
    if (sensorData.pest_detection !== undefined) {
        updatePestDetectionDisplay(sensorData.pest_detection);
    }
    
    // 更新传感器卡片
    updateSensorCards();
    
    // 更新警报面板
    updateAlertsPanel();
    
    // 更新图表
    updateCharts();
    
    // 更新最后数据时间
    updateLastUpdateTime();
}

// 新增函数：更新病虫害检测显示
function updatePestDetectionDisplay(pestStatus) {
    const pestCard = document.getElementById('pest_detection-card');
    const pestValue = document.getElementById('pest_detection-value');
    
    if (pestCard && pestValue) {
        if (pestStatus !== 0) {
            pestValue.textContent = '检测到病虫害';
            pestCard.classList.add('alert');
            pestCard.classList.add('warning');
            
            // 如果有病虫害，确保显示在警报面板
            if (!alerts.some(alert => alert.parameter === 'pest_detection')) {
                alerts.push({
                    parameter: 'pest_detection',
                    type: 'warning',
                    message: '检测到病虫害，请及时处理！'
                });
            }
        } else {
            pestValue.textContent = '无病虫害';
            pestCard.classList.remove('alert');
            pestCard.classList.remove('warning');
            
            // 从警报中移除病虫害警告
            const pestAlertIndex = alerts.findIndex(alert => alert.parameter === 'pest_detection');
            if (pestAlertIndex !== -1) {
                alerts.splice(pestAlertIndex, 1);
            }
        }
    }
}

// 更新传感器卡片显示
function updateSensorCards() {
    for (const [key, config] of Object.entries(sensorConfig)) {
        const valueElement = document.getElementById(`${key}-value`);
        const cardElement = document.getElementById(`${key}-card`);
        
        if (valueElement && sensorData[key] !== undefined) {
            valueElement.textContent = sensorData[key];
            
            // 检查是否需要警报样式
            const isAlert = alerts.some(alert => alert.parameter === key);
            if (isAlert) {
                cardElement.classList.add('alert');
            } else {
                cardElement.classList.remove('alert');
            }
        }
    }
    
    // 更新最后数据时间
    document.getElementById('lastDataTime').textContent = sensorData.timestamp || '--';
}

// 更新警报面板
function updateAlertsPanel() {
    const alertsPanel = document.getElementById('alertsPanel');
    const alertsList = document.getElementById('alertsList');
    const alertCount = document.getElementById('alertCount');
    
    alertCount.textContent = alerts.length;
    
    if (alerts.length > 0) {
        alertsPanel.style.display = 'block';
        alertsList.innerHTML = '';
        
        alerts.forEach(alert => {
            const alertItem = document.createElement('div');
            alertItem.className = `alert-item ${alert.type === 'high' ? 'warning' : ''}`;
            alertItem.innerHTML = `
                <i class="fas fa-exclamation-circle"></i> ${alert.message}
            `;
            alertsList.appendChild(alertItem);
        });
    } else {
        alertsPanel.style.display = 'none';
    }
}

// 初始化图表
function initCharts() {
    const waterQualityCtx = document.getElementById('waterQualityChart').getContext('2d');
    const environmentCtx = document.getElementById('environmentChart').getContext('2d');
    
    // 水质参数图表
    waterQualityChart = new Chart(waterQualityCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: 'pH值',
                    data: [],
                    borderColor: sensorConfig.ph.color,
                    backgroundColor: 'rgba(155, 89, 182, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'TDS值 (ppm)',
                    data: [],
                    borderColor: sensorConfig.tds.color,
                    backgroundColor: 'rgba(26, 188, 156, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '溶解氧 (mg/L)',
                    data: [],
                    borderColor: sensorConfig.dissolved_oxygen.color,
                    backgroundColor: 'rgba(41, 128, 185, 0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: { display: true, text: '水质参数趋势' }
            },
            scales: { y: { beginAtZero: false } }
        }
    });
    
    // 环境参数图表
    environmentChart = new Chart(environmentCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: '温度 (°C)',
                    data: [],
                    borderColor: sensorConfig.temperature.color,
                    backgroundColor: 'rgba(231, 76, 60, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '湿度 (%)',
                    data: [],
                    borderColor: sensorConfig.humidity.color,
                    backgroundColor: 'rgba(52, 152, 219, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '光照强度 (lux)',
                    data: [],
                    borderColor: sensorConfig.light_intensity.color,
                    backgroundColor: 'rgba(243, 156, 18, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: 'CO2 (ppm)',
                    data: [],
                    borderColor: sensorConfig.co2.color,
                    backgroundColor: 'rgba(52, 152, 219, 0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: { display: true, text: '环境参数趋势' }
            },
            scales: { y: { beginAtZero: false } }
        }
    });
}

// 更新图表数据
function updateCharts() {
    if (!waterQualityChart || !environmentChart) return;
    
    const now = new Date();
    const timeLabel = now.getHours() + ':' + now.getMinutes().toString().padStart(2, '0');
    
    // 更新水质图表
    if (waterQualityChart.data.labels.length > 20) {
        waterQualityChart.data.labels.shift();
        waterQualityChart.data.datasets.forEach(dataset => dataset.data.shift());
    }
    
    waterQualityChart.data.labels.push(timeLabel);
    waterQualityChart.data.datasets[0].data.push(sensorData.ph);
    waterQualityChart.data.datasets[1].data.push(sensorData.tds);
    waterQualityChart.data.datasets[2].data.push(sensorData.dissolved_oxygen);
    waterQualityChart.update();
    
    // 更新环境图表
    if (environmentChart.data.labels.length > 20) {
        environmentChart.data.labels.shift();
        environmentChart.data.datasets.forEach(dataset => dataset.data.shift());
    }
    
    environmentChart.data.labels.push(timeLabel);
    environmentChart.data.datasets[0].data.push(sensorData.temperature);
    environmentChart.data.datasets[1].data.push(sensorData.humidity);
    environmentChart.data.datasets[2].data.push(sensorData.light_intensity);
    environmentChart.data.datasets[3].data.push(sensorData.co2);
    environmentChart.update();
}

function updateDeviceButtonState(device, value) {
    const offButton = document.querySelector(`button[onclick="toggleDevice('${device}', 0)"]`);
    const onButton = document.querySelector(`button[onclick="toggleDevice('${device}', 1)"]`);
    
    if (offButton && onButton) {
        if (value === 0) {
            // 设备关闭状态
            offButton.classList.add('active');
            offButton.classList.remove('btn-sm');
            offButton.classList.add('btn-danger', 'btn-sm-active');
            
            onButton.classList.remove('active');
            onButton.classList.remove('btn-primary', 'btn-sm-active');
            onButton.classList.add('btn-sm');
        } else {
            // 设备开启状态
            onButton.classList.add('active');
            onButton.classList.remove('btn-sm');
            onButton.classList.add('btn-success', 'btn-sm-active');
            
            offButton.classList.remove('active');
            offButton.classList.remove('btn-danger', 'btn-sm-active');
            offButton.classList.add('btn-sm');
        }
    }
}

// 设备控制功能
async function toggleDevice(device, value) {
    try {
        const response = await fetch(`${API_BASE_URL}/api/control-device`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ device, value })
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            // 更新本地设备状态
            deviceStatus[device] = value;
            
            // 更新按钮显示状态
            updateDeviceButtonState(device, value);
            
            showNotification(`已${value ? '开启' : '关闭'} ${deviceConfig[device].name}`, 'success');
        } else {
            showNotification('操作失败: ' + result.message, 'error');
        }
    } catch (error) {
        showNotification('操作失败: ' + error.message, 'error');
    }
}

async function setDeviceValue(device, value) {
    try {
        const response = await fetch(`${API_BASE_URL}/api/control-device`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ device, value: parseInt(value) })
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            document.getElementById(`${device}_value`).textContent = value + '%';
            showNotification(`${deviceConfig[device].name} 已设置为 ${value}%`, 'success');
        }
    } catch (error) {
        showNotification('设置失败: ' + error.message, 'error');
    }
}

// 预设模式
async function setPreset(preset) {
    const presets = {
        'all_off': {
            grow_light: 0, alkaline_pump: 0, nutrient_pump: 0,
            fan: 0, heater: 0, acid_pump: 0, humidifier: 0
        }
    };
    
    try {
        const response = await fetch(`${API_BASE_URL}/api/control-multiple`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ controls: presets[preset] })
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            // 更新本地设备状态
            deviceStatus = result.data;
            
            // 更新所有设备按钮状态
            for (const [device, value] of Object.entries(deviceStatus)) {
                if (device !== 'fan') {
                    updateDeviceButtonState(device, value);
                }
            }
            
            showNotification(`已切换到${getPresetName(preset)}模式`, 'success');
        }
    } catch (error) {
        showNotification('切换失败: ' + error.message, 'error');
    }
}

// 阈值设置功能
async function saveThresholds() {
    const thresholds = {};
    
    for (const param of Object.keys(sensorConfig)) {
        const minInput = document.getElementById(`${param}-min`);
        const maxInput = document.getElementById(`${param}-max`);
        
        if (minInput && maxInput) {
            thresholds[param] = {
                min: minInput.value ? parseFloat(minInput.value) : 0,
                max: maxInput.value ? parseFloat(maxInput.value) : 0
            };
        }
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/api/thresholds`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(thresholds)
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            showNotification('阈值设置已保存并发送到设备', 'success');
        } else {
            showNotification('保存失败: ' + result.message, 'error');
        }
    } catch (error) {
        showNotification('保存失败: ' + error.message, 'error');
    }
}

async function loadThresholds() {
    try {
        const response = await fetch(`${API_BASE_URL}/api/thresholds`);
        const result = await response.json();
        
        if (result.status === 'success') {
            const thresholds = result.data;
            
            // 填充表单
            for (const [param, range] of Object.entries(thresholds)) {
                const minInput = document.getElementById(`${param}-min`);
                const maxInput = document.getElementById(`${param}-max`);
                
                if (minInput && maxInput) {
                    minInput.value = range.min;
                    maxInput.value = range.max;
                }
            }
            
            showNotification('已加载当前阈值设置', 'success');
        }
    } catch (error) {
        showNotification('加载失败: ' + error.message, 'error');
    }
}

// 更新设备状态显示
async function updateDeviceStatusDisplay() {
    try {
        const response = await fetch(`${API_BASE_URL}/api/device-status`);
        const result = await response.json();
        
        if (result.status === 'success') {
            deviceStatus = result.data;
            
            for (const [device, value] of Object.entries(deviceStatus)) {
                // 对于开关设备，更新按钮状态
                if (device !== 'fan') {
                    const offButton = document.querySelector(`button[onclick="toggleDevice('${device}', 0)"]`);
                    const onButton = document.querySelector(`button[onclick="toggleDevice('${device}', 1)"]`);
                    
                    if (offButton && onButton) {
                        if (value === 0) {
                            // 设备关闭状态
                            offButton.classList.add('active');
                            offButton.classList.remove('btn-sm');
                            offButton.classList.add('btn-danger', 'btn-sm-active');
                            
                            onButton.classList.remove('active');
                            onButton.classList.remove('btn-primary', 'btn-sm-active');
                            onButton.classList.add('btn-sm');
                        } else {
                            // 设备开启状态
                            onButton.classList.add('active');
                            onButton.classList.remove('btn-sm');
                            onButton.classList.add('btn-success', 'btn-sm-active');
                            
                            offButton.classList.remove('active');
                            offButton.classList.remove('btn-danger', 'btn-sm-active');
                            offButton.classList.add('btn-sm');
                        }
                    }
                }
                
                // 对于风扇，保持原来的显示方式
                const valueElement = document.getElementById(`${device}_value`);
                const sliderElement = document.getElementById(`${device}_slider`);
                
                if (valueElement) {
                    valueElement.textContent = value + '%';
                }
                
                if (sliderElement) {
                    sliderElement.value = value;
                }
            }
        }
    } catch (error) {
        console.error('获取设备状态失败:', error);
    }
}

// 图像显示功能
function initImageDisplay() {
    const noImageMessage = document.getElementById('noImageMessage');
    const cameraImage = document.getElementById('cameraImage');
    
    if (noImageMessage && cameraImage) {
        // 初始状态显示无图像消息
        noImageMessage.style.display = 'flex';
        cameraImage.style.display = 'none';
    }
}

function updateImageDisplay(imageData) {
    const cameraImage = document.getElementById('cameraImage');
    const noImageMessage = document.getElementById('noImageMessage');
    const imageStatus = document.getElementById('imageStatus');
    const imageTime = document.getElementById('imageTime');
    
    if (cameraImage && imageData && imageData.image_data) {
        // 保存当前图像数据
        currentImageData = imageData;
        
        // 显示图像，隐藏无图像消息
        cameraImage.src = imageData.image_data;
        cameraImage.style.display = 'block';
        if (noImageMessage) {
            noImageMessage.style.display = 'none';
        }
        
        // 更新状态和时间
        if (imageStatus) {
            imageStatus.textContent = '图像已更新';
            imageStatus.style.color = 'var(--success)';
        }
        
        if (imageTime) {
            imageTime.textContent = imageData.timestamp || '刚刚';
        }
        
        // 3秒后恢复状态显示
        setTimeout(() => {
            if (imageStatus) {
                imageStatus.textContent = '监控中...';
                imageStatus.style.color = 'var(--gray)';
            }
        }, 3000);
        
        console.log('✅ 图像显示已更新');
    }
}

function requestImage() {
    const imageStatus = document.getElementById('imageStatus');
    
    if (imageStatus) {
        imageStatus.textContent = '请求图像中...';
        imageStatus.style.color = 'var(--warning)';
    }
    
    if (socket && socket.connected) {
        // 通过WebSocket请求图像
        socket.emit('request_image');
        console.log('📷 已发送图像请求');
    } else {
        // 备用方案：通过HTTP API请求
        fetch(`${API_BASE_URL}/api/current-image`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    updateImageDisplay(data);
                } else {
                    showNotification('获取图像失败: ' + data.message, 'error');
                    if (imageStatus) {
                        imageStatus.textContent = '获取失败';
                        imageStatus.style.color = 'var(--danger)';
                    }
                }
            })
            .catch(error => {
                console.error('请求图像失败:', error);
                showNotification('请求图像失败', 'error');
                if (imageStatus) {
                    imageStatus.textContent = '请求失败';
                    imageStatus.style.color = 'var(--danger)';
                }
            });
    }
}

function takeSnapshot() {
    const cameraImage = document.getElementById('cameraImage');
    if (cameraImage && cameraImage.style.display !== 'none') {
        const link = document.createElement('a');
        link.download = `snapshot_${new Date().getTime()}.jpg`;
        link.href = cameraImage.src;
        link.click();
        showNotification('图像已保存', 'success');
    } else {
        showNotification('无可用图像', 'error');
    }
}

// 模式控制功能
function initModeControls() {
    // 初始状态：持续推流模式
    updateModeDisplay();
    
    // 从服务器获取当前模式状态
    fetch(`${API_BASE_URL}/api/mode-status`)
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                currentMode = data.stream_mode ? 'stream' : 'on_demand';
                streamPaused = data.stream_paused;
                updateModeDisplay();
            }
        })
        .catch(error => {
            console.error('获取模式状态失败:', error);
        });
}

function updateModeDisplay() {
    const streamModeBtn = document.getElementById('streamModeBtn');
    const onDemandModeBtn = document.getElementById('onDemandModeBtn');
    const streamControls = document.getElementById('streamControls');
    const captureControls = document.getElementById('captureControls');
    const pauseStreamBtn = document.getElementById('pauseStreamBtn');
    const resumeStreamBtn = document.getElementById('resumeStreamBtn');
    const captureStatus = document.getElementById('captureStatus');
    
    // 更新模式按钮状态
    if (streamModeBtn && onDemandModeBtn) {
        if (currentMode === 'stream') {
            streamModeBtn.classList.add('active');
            onDemandModeBtn.classList.remove('active');
        } else {
            streamModeBtn.classList.remove('active');
            onDemandModeBtn.classList.add('active');
        }
    }
    
    // 显示/隐藏控制面板
    if (streamControls && captureControls) {
        if (currentMode === 'stream') {
            streamControls.style.display = 'flex';
            captureControls.style.display = 'none';
        } else {
            streamControls.style.display = 'none';
            captureControls.style.display = 'flex';
        }
    }
    
    // 更新推流控制按钮状态
    if (pauseStreamBtn && resumeStreamBtn) {
        if (streamPaused) {
            pauseStreamBtn.style.display = 'none';
            resumeStreamBtn.style.display = 'inline-block';
        } else {
            pauseStreamBtn.style.display = 'inline-block';
            resumeStreamBtn.style.display = 'none';
        }
    }
    
    // 更新拍照模式状态显示
    if (captureStatus) {
        if (currentMode === 'on_demand') {
            captureStatus.textContent = streamPaused ? '设备休眠中' : '设备拍照中...';
            captureStatus.style.color = streamPaused ? 'var(--gray)' : 'var(--warning)';
        }
    }
}

function switchMode(mode) {
    if (mode === currentMode) return;
    
    const previousMode = currentMode;
    currentMode = mode;
    
    // 立即更新UI
    updateModeDisplay();
    
    // 发送模式切换请求到服务器
    fetch(`${API_BASE_URL}/api/switch-mode`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode: mode })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            showNotification(data.message, 'success');
            currentMode = data.stream_mode ? 'stream' : 'on_demand';
            streamPaused = data.stream_paused;
            updateModeDisplay();
        } else {
            // 恢复之前的模式
            currentMode = previousMode;
            updateModeDisplay();
            showNotification('模式切换失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('模式切换失败:', error);
        // 恢复之前的模式
        currentMode = previousMode;
        updateModeDisplay();
        showNotification('模式切换失败', 'error');
    });
}

function controlStream(action) {
    if (currentMode !== 'stream') return;
    
    fetch(`${API_BASE_URL}/api/control-stream`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: action })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            showNotification(data.message, 'success');
            streamPaused = data.stream_paused;
            updateModeDisplay();
        } else {
            showNotification('操作失败: ' + data.message, 'error');
        }
    })
    .catch(error => {
        console.error('控制推流失败:', error);
        showNotification('控制推流失败', 'error');
    });
}

function requestCapture() {
    if (currentMode !== 'on_demand') return;
    
    // 立即更新UI状态
    streamPaused = false;
    updateModeDisplay();
    
    fetch(`${API_BASE_URL}/api/request-capture`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            showNotification(data.message, 'success');
            streamPaused = data.stream_paused;
            // 注意：拍照完成后，streamPaused 会自动变为 true
        } else {
            showNotification('拍照请求失败: ' + data.message, 'error');
            streamPaused = true;
            updateModeDisplay();
        }
    })
    .catch(error => {
        console.error('拍照请求失败:', error);
        showNotification('拍照请求失败', 'error');
        streamPaused = true;
        updateModeDisplay();
    });
}

// 辅助函数
function getPresetName(preset) {
    const names = {
        'all_off': '全部关闭'
    };
    return names[preset] || preset;
}

function updateLastUpdateTime() {
    const now = new Date();
    document.getElementById('lastUpdateTime').textContent = 
        now.toLocaleDateString() + ' ' + now.toLocaleTimeString();
}

function showNotification(message, type) {
    // 简单的通知实现
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 5px;
        color: white;
        z-index: 1000;
        font-weight: 600;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        background: ${type === 'success' ? 'var(--success)' : 'var(--danger)'};
    `;
    
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        if (document.body.contains(notification)) {
            document.body.removeChild(notification);
        }
    }, 3000);
}

// 模型上传相关变量
let selectedModelFile = null;

// 初始化模型上传功能
function initModelUpload() {
    const fileInput = document.getElementById('modelFileInput');
    const uploadArea = document.getElementById('modelUploadArea');
    
    // 点击上传区域触发文件选择
    uploadArea.addEventListener('click', function() {
        fileInput.click();
    });
    
    // 拖放功能
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = 'var(--primary)';
        uploadArea.style.background = '#f0f8ff';
    });
    
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = '#dee2e6';
        uploadArea.style.background = '#f8f9fa';
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        uploadArea.style.borderColor = '#dee2e6';
        uploadArea.style.background = '#f8f9fa';
        
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleFileSelection(files[0]);
        }
    });
    
    // 文件选择变化
    fileInput.addEventListener('change', function(e) {
        if (e.target.files.length > 0) {
            handleFileSelection(e.target.files[0]);
        }
    });
}

// 处理文件选择
function handleFileSelection(file) {
    // 检查文件类型
    if (!file.name.toLowerCase().endsWith('.kmodel')) {
        showNotification('请选择 .kmodel 格式的文件', 'error');
        return;
    }
    
    selectedModelFile = file;
    
    // 显示文件信息
    document.getElementById('modelFileName').textContent = file.name;
    document.getElementById('modelFileSize').textContent = formatFileSize(file.size);
    document.getElementById('modelFileDate').textContent = new Date(file.lastModified).toLocaleString();
    
    // 显示模型信息面板，隐藏上传区域
    document.getElementById('modelUploadArea').style.display = 'none';
    document.getElementById('modelInfo').style.display = 'block';
    
    // 重置进度和状态
    resetUploadProgress();
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 重置上传进度
function resetUploadProgress() {
    document.getElementById('uploadProgress').style.display = 'none';
    document.getElementById('progressFill').style.width = '0%';
    document.getElementById('progressText').textContent = '0%';
    
    const statusElement = document.getElementById('uploadStatus');
    statusElement.textContent = '';
    statusElement.className = 'upload-status';
}

// 更新上传进度
function updateUploadProgress(percentage) {
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');
    const uploadProgress = document.getElementById('uploadProgress');
    
    uploadProgress.style.display = 'flex';
    progressFill.style.width = percentage + '%';
    progressText.textContent = percentage + '%';
    
    // 添加过渡动画
    progressFill.style.transition = 'width 0.3s ease';
}

// 显示上传状态
function showUploadStatus(message, type) {
    const statusElement = document.getElementById('uploadStatus');
    statusElement.textContent = message;
    statusElement.className = `upload-status ${type}`;
    statusElement.style.display = 'block';
}

// 清除文件选择
function clearModelSelection() {
    selectedModelFile = null;
    document.getElementById('modelFileInput').value = '';
    
    // 显示上传区域，隐藏信息面板
    document.getElementById('modelUploadArea').style.display = 'block';
    document.getElementById('modelInfo').style.display = 'none';
    
    resetUploadProgress();
}

// 修改：重置上传状态
function resetUploadState() {
    uploadInProgress = false;
    uploadPaused = false;
    currentUploadProgress = 0;
    updateUploadControls(false, false);
    
    // 重新启用取消选择按钮
    document.querySelector('button[onclick="clearModelSelection()"]').disabled = false;
}

// 处理上传进度
function handleUploadProgress(data) {
    if (data.progress >= 0) {
        currentUploadProgress = data.progress;
        updateUploadProgress(data.progress);
        
        if (data.progress === 100) {
            showUploadStatus('模型文件上传完成！', 'success');
            showNotification('模型文件上传完成', 'success');
            resetUploadState();
        }
    } else if (data.error) {
        showUploadStatus('上传失败: ' + data.error, 'error');
        resetUploadState();
    }
}

// 新增：更新上传控制按钮状态
function updateUploadControls(inProgress, isPaused) {
    const uploadBtn = document.getElementById('uploadModelBtn');
    const pauseBtn = document.getElementById('pauseUploadBtn');
    const resumeBtn = document.getElementById('resumeUploadBtn');
    const cancelBtn = document.getElementById('cancelUploadBtn');
    
    if (inProgress) {
        uploadBtn.style.display = 'none';
        cancelBtn.style.display = 'inline-block';
        
        if (isPaused) {
            pauseBtn.style.display = 'none';
            resumeBtn.style.display = 'inline-block';
        } else {
            pauseBtn.style.display = 'inline-block';
            resumeBtn.style.display = 'none';
        }
    } else {
        uploadBtn.style.display = 'inline-block';
        pauseBtn.style.display = 'none';
        resumeBtn.style.display = 'none';
        cancelBtn.style.display = 'none';
    }
}

// 上传模型文件
async function uploadModel() {
    if (!selectedModelFile) {
        showNotification('请先选择模型文件', 'error');
        return;
    }
    
    if (uploadInProgress) {
        showNotification('已有上传任务在进行中', 'error');
        return;
    }
    
    try {
        uploadInProgress = true;
        uploadPaused = false;
        currentUploadProgress = 0;
        
        // 更新界面状态
        updateUploadControls(true, false);
        
        // 显示上传状态和初始进度
        showUploadStatus('开始上传模型文件...', 'info');
        updateUploadProgress(0);
        
        // 读取文件
        const arrayBuffer = await readFileAsArrayBuffer(selectedModelFile);
        
        // 发送到后端 - 进度将通过WebSocket实时更新
        const response = await fetch(`${API_BASE_URL}/api/upload-model`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/octet-stream',
                'X-File-Name': encodeURIComponent(selectedModelFile.name),
                'X-File-Size': selectedModelFile.size.toString()
            },
            body: arrayBuffer
        });
        
        const result = await response.json();
        
        if (result.status !== 'success') {
            throw new Error(result.message);
        }
        
    } catch (error) {
        console.error('上传模型失败:', error);
        if (!uploadInProgress) {
            // 如果是用户取消，不显示错误
            return;
        }
        showUploadStatus('上传失败: ' + error.message, 'error');
        showNotification('模型上传失败: ' + error.message, 'error');
        resetUploadState();
    }
}

// 新增：暂停上传
async function pauseUpload() {
    if (!uploadInProgress || uploadPaused) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/api/pause-upload`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            uploadPaused = true;
            updateUploadControls(true, true);
            showUploadStatus('上传已暂停', 'info');
            showNotification('模型上传已暂停', 'warning');
        } else {
            showNotification('暂停失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('暂停上传失败:', error);
        showNotification('暂停上传失败', 'error');
    }
}

// 新增：恢复上传
async function resumeUpload() {
    if (!uploadInProgress || !uploadPaused) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/api/resume-upload`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            uploadPaused = false;
            updateUploadControls(true, false);
            showUploadStatus('上传已恢复...', 'info');
            showNotification('模型上传已恢复', 'success');
        } else {
            showNotification('恢复失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('恢复上传失败:', error);
        showNotification('恢复上传失败', 'error');
    }
}

// 新增：取消上传
async function cancelUpload() {
    if (!uploadInProgress) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/api/cancel-upload`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (result.status === 'success') {
            resetUploadState();
            showUploadStatus('上传已取消', 'info');
            showNotification('模型上传已取消', 'warning');
        } else {
            showNotification('取消失败: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('取消上传失败:', error);
        showNotification('取消上传失败', 'error');
    }
}

// 新增：处理上传暂停
function handleUploadPaused(data) {
    uploadPaused = true;
    updateUploadControls(true, true);
    showUploadStatus(`上传已暂停 (${data.current_chunk}/${data.total_chunks} 包)`, 'info');
}

// 新增：处理上传取消
function handleUploadCancelled() {
    resetUploadState();
    showUploadStatus('上传已取消', 'info');
}



// 读取文件为ArrayBuffer
function readFileAsArrayBuffer(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = function(e) {
            resolve(e.target.result);
        };
        reader.onerror = function(e) {
            reject(new Error('文件读取失败'));
        };
        reader.readAsArrayBuffer(file);
    });
}

// 在initApp函数中初始化模型上传
function initApp() {
    initConnection();
    initCharts();
    initSensorCards();
    initImageDisplay();
    initModeControls();
    initModelUpload(); // 新增
    updateLastUpdateTime();
    
    setInterval(updateLastUpdateTime, 30000);
    setInterval(updateDeviceStatusDisplay, 5000);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initApp);